package com.yunjing.elasticjob.service.impl;

import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.exception.JobSystemException;
import com.dangdang.ddframe.job.lite.api.JobScheduler;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import com.yunjing.elasticjob.elastic.ElasticJobListener;
import com.yunjing.elasticjob.entity.JobConfig;
import com.yunjing.elasticjob.service.ElasticJobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author zhiqi.shao
 * @Date 2018/6/15 9:00
 */
@Slf4j
@Service
public class ElasticJobServiceImpl implements ElasticJobService {


    @Resource
    private ElasticJobListener elasticJobListener;


    @Resource
    private ZookeeperRegistryCenter registryCenter;


    /**
     *
     * @param jobConfig
     * @param jobClass
     * @param shardingTotalCount
     * @return
     */
    @Override
    public boolean addJob(JobConfig jobConfig, Class<? extends SimpleJob> jobClass, int shardingTotalCount) {
        JobCoreConfiguration coreConfig = JobCoreConfiguration.
                newBuilder(jobConfig.getName(), jobConfig.getCron(), shardingTotalCount)
                //开启任务转移，需要配合下面的monitorExecution
                .failover(true)
                //任务参数
                .jobParameter(jobConfig.getId().toString())
                //测试分片数，测试两片
                .shardingItemParameters("0=0,1=1")
                .build();
        SimpleJobConfiguration simpleJobConfig = new SimpleJobConfiguration(coreConfig, jobClass.getCanonicalName());
        //JobScheduler jobScheduler = new JobScheduler(registryCenter, LiteJobConfiguration.newBuilder(simpleJobConfig).monitorExecution(true).overwrite(true).build(),elasticJobListener);
        JobScheduler jobScheduler = new JobScheduler(registryCenter,
                LiteJobConfiguration.newBuilder(simpleJobConfig).monitorExecution(true).overwrite(true).build());
        try {
            jobScheduler.init();
        } catch (JobSystemException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * 删除任务
     *
     * key is job name
     */
    public void removeJob(String key){
        registryCenter.remove("/"+key);
    }




}
